<template>
  <a-drawer
    :width="prop.width"
    :fullscreen="isFull"
    v-model:visible="drawer.visible"
    :on-before-ok="drawer.submit"
    :title="prop.title"
    @cancel="drawer.cancel"
    @before-close="handleBeforeClose"
    :ok-text="okText"
    :cancel-text="cancelText"
  >
    <slot name="body" />
    <ma-form ref="maFormRef" :columns="formColumns" v-model="form" :options="{ ...options, showButtons: false }" />
  </a-drawer>
</template>

<script setup>
import MaForm from "@/components/MaForm/index.vue";
import { setModalSizeEvent } from "@/utils/common";

const emit = defineEmits(["visible", "validateError", "open", "cancel", "close"]);
const form = ref({});
const formColumns = ref([]);
const prop = defineProps({
  width: { type: Number, default: 600 }, // drawer框大小
  isFull: { type: Boolean, default: false }, // 是否全屏
  title: { type: String, default: "" }, // 弹出框标题
  column: { type: Array, default: [] }, // ma-form字段
  columns: { type: Array, default: [] }, // ma-form字段 别名
  infoColumns: { type: Array, default: [] },
  infoData: { type: Object, default: {} },
  defaultVisible: { type: Boolean, default: false }, // 默认隐藏
  options: { type: Object, default: {} }, // MaForm 属性
  okText: { type: String, default: "保存" },
  cancelText: { type: String, default: "取消" },
  submit: {
    type: Function,
    default: () => {}
  }
});

const isFull = ref(prop.isFull);
setModalSizeEvent(config => {
  isFull.value = config.isFull;
});

formColumns.value = [...prop.column, ...prop.columns];
let submitEvent = prop.submit;

const maFormRef = ref();

const handleBeforeClose = () => {
  maFormRef.value?.resetForm();
};

const drawer = reactive({
  visible: prop.defaultVisible,
  open(formData, infoData = {}) {
    drawer.visible = true;
    for (let [key, value] of Object.entries(formData)) {
      form.value[key] = value;
    }
    for (let [key, value] of Object.entries(infoData)) {
      prop.infoData[key] = value;
    }
    emit("open", formData, infoData);
  },
  onSubmit(func) {
    submitEvent = func;
    return this;
  },
  close() {
    drawer.visible = false;
  },
  async submit() {
    let validate = await maFormRef.value.validateForm();
    if (validate) {
      emit("validateError", validate);
      return false;
    }
    return submitEvent(form._rawValue);
  },
  cancel() {
    emit("cancel");
  }
});

watch(
  () => drawer.visible,
  vl => {
    emit("visible", drawer.visible);
  },
  { immediate: true }
);

const getAttr = key => {
  return form.value[key];
};

defineExpose({
  open: drawer.open,
  close: drawer.close,
  form: form,
  getAttr,
  formRef: maFormRef,
  onSubmit: drawer.onSubmit
});
</script>
